<template>
  <view class="order-container">
    <!-- 搜索框 -->
    <view class="search-bar">
      <input class="search-input" type="text" placeholder="搜索商品名称" v-model="searchKeyword" @confirm="searchProducts" />
      <text class="search-icon" @click="searchProducts">🔍</text>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 左侧分类导航 -->
      <view class="category-sidebar">
        <scroll-view scroll-y class="category-scroll">
          <text
            class="category-item"
            :class="{ active: activeCategory === category.id }"
            v-for="category in categories"
            :key="category.id"
            @click="selectCategory(category.id)"
          >
            {{ category.name }}
          </text>
        </scroll-view>
      </view>

      <!-- 右侧商品列表 -->
      <view class="product-list">
        <scroll-view scroll-y class="product-scroll">
          <!-- 配送信息 Banner -->
          <view class="delivery-banner">
            <text class="banner-title">服务宗旨</text>
            <text class="banner-subtitle">美味源自用心,服务始于微笑</text>
          </view>
          
          <!-- 商品信息 -->
          <view class="food-items-section">
            <!-- 显示已选商品按钮 -->
            <view class="section-header" v-if="totalCount > 0" @click="showCartModal = true">
              <text class="section-title">已选商品</text>
              <text class="item-count">共{{ totalCount }}件 ></text>
            </view>
            
            <view v-if="products.length === 0" class="empty-list">
              <text class="empty-text">暂无菜品</text>
            </view>
            
            <!-- 商品列表 -->
            <view class="food-list" v-else>
              <view class="food-item" v-for="(product, index) in displayedProducts" :key="product.id">
                <image class="food-image" :src="product.image" mode="aspectFill"></image>
                <view class="food-info">
                  <text class="food-name">{{ product.name }}</text>
                  <view class="food-price-quantity">
                    <text class="food-price">¥ {{ product.price.toFixed(2) }}</text>
                  </view>
                </view>
                <view class="quantity-controls" v-if="product.status === 0">
                  <text class="control-btn minus" @click="decreaseQuantity(index)">-</text>
                  <text class="quantity">{{ product.quantity }}</text>
                  <text class="control-btn plus" @click="increaseQuantity(index)">+</text>
                </view>
                <view class="sold-out" v-else>
                  <text>{{ product.status === 1 ? '已售罄' : '已下架' }}</text>
                </view>
              </view>
            </view>
            
            <!-- 展开/收起按钮 -->
            <view class="expand-section" v-if="products.length > 3" @click="isExpanded = !isExpanded">
              <text class="expand-text">{{ isExpanded ? '收起' : `展开剩余${remainingItems}件` }}</text>
              <text class="expand-icon" :class="{ 'expanded': isExpanded }">></text>
            </view>
          </view>

        </scroll-view>
      </view>
    </view>

    <!-- 底部汇总和提交订单 -->
    <view class="footer-bar">
      <view class="total-info">
        <text class="total-count">共计{{ totalCount }}件</text>
        <text class="total-price">¥ {{ totalPrice.toFixed(2) }}</text>
      </view>
      <button class="checkout-button" @click="showCartModal = true" :disabled="totalCount === 0" :class="{'button-disabled': totalCount === 0}">提交订单</button>
    </view>

    <!-- 购物车模态框 -->
    <view class="cart-modal-overlay" v-if="showCartModal" @click.self="showCartModal = false">
      <view class="cart-modal-content">
        <!-- 模态框头部 -->
        <view class="modal-header">
          <text class="modal-title">已选菜品</text>
          <text class="close-button" @click="showCartModal = false">×</text>
        </view>

        <view v-if="cartItems.length === 0" class="empty-cart">
          <text class="empty-text">购物车是空的</text>
          <text class="empty-tip">请先添加菜品</text>
        </view>

        <!-- 已选商品列表 -->
        <scroll-view scroll-y class="selected-products-list" v-else>
          <view class="selected-product-item" v-for="product in products.filter(p => p.quantity > 0)" :key="product.id">
             <image class="selected-product-image" :src="product.image" mode="aspectFill"></image>
            <view class="selected-product-info">
              <text class="selected-product-name">{{ product.name }}</text>
              <text class="selected-product-price">¥ {{ product.price.toFixed(2) }}</text>
            </view>
            <view class="selected-quantity-controls">
              <text class="control-btn minus" @click="updateCartItemQuantity(product.id, -1)">-</text>
              <text class="selected-quantity">{{ product.quantity }}</text>
              <text class="control-btn plus" @click="updateCartItemQuantity(product.id, 1)">+</text>
            </view>
          </view>
        </scroll-view>

        <!-- 模态框底部汇总和提交订单 -->
        <view class="modal-footer-bar">
          <view class="modal-total-info">
             <text class="modal-total-label">已选</text>
            <text class="modal-total-count">{{ totalCount }}件</text>
            <text class="modal-total-price">¥ {{ totalPrice.toFixed(2) }}</text>
          </view>
          <button class="pay-button" @click="submitOrder" :disabled="totalCount === 0" :class="{'button-disabled': totalCount === 0}">提交订单</button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
// 从正确的位置导入API
import { dishApi, orderApi, boardApi } from '../../utils/api'

export default {
  data() {
    return {
      title: '点餐',
      searchKeyword: '',
      activeCategory: null,
      categories: [], // 分类数据
      products: [], // 商品列表数据
      totalCount: 0,
      totalPrice: 0,
      showCartModal: false, // 控制购物车模态框的显示隐藏
      isExpanded: false, // 控制商品列表展开/收起
      token: uni.getStorageSync('token'), // 获取存储的 token
      allProducts: [], // 存储所有菜品，用于分类筛选
      boardId: null // 新增的boardId
    }
  },
  computed: {
    // 展示的商品列表
    displayedProducts() {
      return this.isExpanded ? this.products : this.products.slice(0, 3);
    },
    // 剩余未显示的商品数量
    remainingItems() {
      return this.products.length - 3;
    },
    // 购物车商品列表，与payment.vue中保持一致
    cartItems() {
      return this.products.filter(p => p.quantity > 0).map(p => ({
        dishId: p.id,
        dishName: p.name,
        dishImage: p.image.replace('https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/', ''),
        price: p.price,
        quantity: p.quantity,
        description: p.description
      }));
    }
  },
  onLoad(options) {
    // 获取页面参数中的boardId
    if (options.boardId) {
      this.boardId = parseInt(options.boardId);
      console.log('获取到餐桌ID:', this.boardId);
    }
    
    this.fetchCategories(); // 获取分类数据，会在回调中获取菜品数据
  },
  methods: {
    fetchCategories() {
      // 使用正确的API获取菜品分类数据
      dishApi.getDishTypes().then(res => {
        console.log('获取到的分类数据：', res);
        
        if (res.code === 200) { 
          // 处理菜品分类数据，根据实际API返回格式调整
          // API返回是字符串数组 ["热门","冷菜","热菜"...]
          this.categories = res.data.map((name, index) => ({
            id: index + 1, // 使用索引+1作为分类ID，从1开始
            name: name
          }));
          
          // 设置第一个分类为默认选中
          this.activeCategory = this.categories[0]?.id || null;
          
          // 获取分类后立即获取菜品
          this.fetchProducts();
        } else {
          console.error('获取分类失败:', res.msg);
          uni.showToast({
            title: '获取分类失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('获取分类出错:', error);
        uni.showToast({
          title: '获取分类失败',
          icon: 'none'
        });
      });
    },
    fetchProducts() {
      // 使用正确的API获取菜品数据
      dishApi.getDishList().then(res => {
        console.log('获取到的菜品数据：', res);
        
        if (res.code === 200) {
          // 保存所有菜品数据，用于分类筛选
          this.allProducts = res.data.map(dish => ({
            id: dish.dishId,
            name: dish.dishName,
            description: dish.dishDescribe || '暂无描述',
            price: dish.price || 0,
            quantity: 0, // 初始化数量为0
            image: dish.dishImage ? `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${dish.dishImage}` : '/static/product-placeholder.png',
            categoryId: dish.dtId + 1, // 将菜品类型编号加1，匹配分类ID (1-7)
            // 注意：根据用户说明，dishStatus为0是在售，1是售罄
            status: dish.dishStatus // 0:正常销售 1:售罄
          }));
          
          // 根据选中分类过滤菜品
          this.filterProductsByCategory();
        } else {
          console.error('获取菜品失败:', res.msg);
          uni.showToast({
            title: '获取菜品失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('获取菜品出错:', error);
        uni.showToast({
          title: '获取菜品失败',
          icon: 'none'
        });
      });
    },
    // 根据选中分类过滤菜品
    filterProductsByCategory() {
      // 根据选中分类过滤菜品
      this.products = this.allProducts.filter(product => product.categoryId === this.activeCategory);
      
      // 如果有搜索关键词，进一步过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase();
        this.products = this.products.filter(product => 
          product.name.toLowerCase().includes(keyword) || 
          product.description.toLowerCase().includes(keyword)
        );
      }
      
      this.updateTotal();
      console.log('过滤后的菜品数据：', this.products);
    },
    searchProducts() {
      // 只需要在已有的数据中搜索
      this.filterProductsByCategory();
    },
    selectCategory(categoryId) {
      this.activeCategory = categoryId;
      this.filterProductsByCategory();
    },
    increaseQuantity(index) {
      // 只有状态为0的菜品才能增加数量
      if (this.products[index].status === 0) {
        this.products[index].quantity++;
        this.updateTotal();
      }
    },
    decreaseQuantity(index) {
      if (this.products[index].quantity > 0) {
        this.products[index].quantity--;
        this.updateTotal();
      }
    },
    // 更新购物车内菜品数量
    updateCartItemQuantity(productId, change) {
      const index = this.products.findIndex(p => p.id === productId);
      if (index !== -1) {
        if (change > 0) {
          this.increaseQuantity(index);
        } else {
          this.decreaseQuantity(index);
        }
      }
    },
    updateTotal() {
      let count = 0;
      let price = 0;
      this.products.forEach(product => {
        count += product.quantity;
        price += product.quantity * product.price;
      });
      this.totalCount = count;
      this.totalPrice = price;
    },
    // 检查购物车菜品有效性
    checkCartItems() {
      try {
        // 从购物车中提取菜品ID
        const dishIds = this.cartItems.map(item => item.dishId)
        
        if (dishIds.length === 0) {
          return false;
        }
        
        console.log('提交订单菜品ID列表:', dishIds)
        return true;
      } catch (error) {
        console.error('检查购物车菜品失败:', error);
        return false;
      }
    },
    // 提交订单
    submitOrder() {
      // 检查购物车是否有商品
      if (this.totalCount === 0) {
        uni.showToast({
          title: '请先选择商品',
          icon: 'none'
        });
        return;
      }
      
      // 检查购物车菜品有效性
      const canProceed = this.checkCartItems();
      
      if (canProceed) {
        // 获取token中的用户ID
        const token = uni.getStorageSync('token');
        
        // 准备订单数据，按照Java实体类CustomerOrder的结构
        const orderData = {
          boardId: this.boardId || 1, // 从页面参数获取餐桌ID，默认为1
          totalAmount: this.totalPrice, // 总金额
          discountAmount: 0, // 优惠金额，留空
          payableAmount: this.totalPrice, // 实付金额，与总金额相同
          orderType: 1, // 订单类型，默认1
          orderStatus: null, // 订单状态，留空
          placeOrderTime: new Date().toISOString(), // 下单时间，当前时间
          paymentTime: null, // 支付时间，留空
          remark: "", // 订单备注，留空
          shippingAddress: "", // 配送地址，留空（表示堂食）
          uId: token // 操作人，从token获取
        };
        
        console.log('准备提交订单:', orderData);
        
        // 调用提交订单的API
        orderApi.createOrder(orderData).then(res => {
          if (res.code === 200) {
            console.log('订单创建成功:', res);
            
            // 获取订单ID
            const orderId = res.data.orderId || res.data;
            
            // 创建订单项
            this.createOrderItems(orderId);
            
          } else {
            uni.showToast({
              title: res.msg || '订单提交失败',
              icon: 'none'
            });
          }
        }).catch(error => {
          console.error('提交订单失败:', error);
          uni.showToast({
            title: '订单提交失败',
            icon: 'none'
          });
        });
      }
    },
    
    // 创建订单项
    createOrderItems(orderId) {
      // 获取所有选中的菜品
      const selectedItems = this.cartItems;
      
      if (selectedItems.length === 0) {
        uni.showToast({
          title: '没有选中的菜品',
          icon: 'none'
        });
        return;
      }
      
      // 显示加载提示
      uni.showLoading({
        title: '正在创建订单项...'
      });
      
      // 为每个菜品创建订单项
      const promises = selectedItems.map(item => {
        return orderApi.createOrderItem(orderId, item.dishId, item.quantity);
      });
      
      // 等待所有订单项创建完成
      Promise.all(promises).then(results => {
        uni.hideLoading();
        
        // 检查是否所有订单项都创建成功
        const allSuccess = results.every(res => res.code === 200);
        
        if (allSuccess) {
          // 新增：修改餐桌状态为正在就餐
          const boardObj = {
            boardId: this.boardId,
            boardStatus: 2 // 2=REPAST
          };
          boardApi.updBoard(boardObj).then(res => {
            if (res.code === 200) {
              uni.showToast({
                title: '订单创建成功',
                icon: 'success'
              });
              // 清空购物车
              this.resetCart();
              // 关闭模态框
              this.showCartModal = false;
            } else {
              uni.showToast({
                title: '餐桌状态更新失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            uni.showToast({
              title: '餐桌状态更新失败',
              icon: 'none'
            });
          });
        } else {
          // 如果有失败的订单项
          const failedCount = results.filter(res => res.code !== 200).length;
          uni.showToast({
            title: `${failedCount}个菜品添加失败`,
            icon: 'none'
          });
        }
      }).catch(error => {
        uni.hideLoading();
        console.error('创建订单项失败:', error);
        uni.showToast({
          title: '创建订单项失败',
          icon: 'none'
        });
      });
    },
    // 重置购物车
    resetCart() {
      // 将所有商品数量重置为0
      this.products.forEach(product => {
        product.quantity = 0;
      });
      this.updateTotal();
    },
    // 获取orderStore的辅助方法
    getOrderStore() {
      try {
        // 尝试导入store
        const { useOrderStore } = require('../../store/order');
        return useOrderStore();
      } catch (error) {
        console.error('无法获取 orderStore:', error);
        return null;
      }
    }
  }
}
</script>

<style>
.order-container {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 使页面高度占满视口 */
  overflow: hidden; /* 防止内容溢出 */
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #C70209; /* 红色背景 */
}

.search-input {
  flex: 1;
  height: 70rpx;
  background-color: #ffffff; /* 白色背景 */
  border-radius: 35rpx; /* 圆角 */
  padding: 0 30rpx;
  font-size: 28rpx;
}

.search-icon {
  margin-left: 20rpx;
  color: #ffffff;
  font-size: 36rpx;
}

.main-content {
  flex: 1; /* 占据剩余空间 */
  display: flex;
  overflow: hidden; /* 防止内容溢出 */
}

.category-sidebar {
  width: 200rpx; /* 左侧分类宽度 */
  background-color: #f8f8f8; /* 浅灰色背景 */
  padding: 20rpx 0;
  /* overflow-y: auto; /* 允许滚动 */ /* 替换为 scroll-view */
}

.category-scroll {
  height: 100%; /* 使 scroll-view 填充父容器高度 */
}

.category-item {
  display: block;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333; /* 默认字体颜色 */
  text-align: center;
}

.category-item.active {
  color: #C70209; /* 选中分类字体颜色 */
  font-weight: bold;
  position: relative;
}

.category-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 10rpx;
  height: 60%; /* 根据需要调整高度 */
  background-color: #C70209; /* 红色指示条 */
}

.product-list {
  flex: 1; /* 占据剩余空间 */
  padding: 20rpx;
  /* overflow-y: auto; /* 允许滚动 */ /* 替换为 scroll-view */
}

.product-scroll {
   height: 100%; /* 使 scroll-view 填充父容器高度 */
}

.delivery-banner {
  background-color: #C70209; /* 红色背景 */
  color: #ffffff;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.banner-title {
  font-size: 32rpx;
  font-weight: bold;
}

.banner-subtitle {
  font-size: 28rpx;
  opacity: 0.9;
}

/* 从payment.vue复制的样式 */
.food-items-section {
  background: #fff;
  padding: 20rpx 16rpx;
  margin-bottom: 12rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.item-count {
  font-size: 26rpx;
  color: #999;
}

.food-list {
  width: 100%;
}

.food-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.food-item:last-child {
  border-bottom: none;
}

.food-image {
  width: 150rpx;
  height: 150rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  background-color: #f5f5f5;
  object-fit: cover;
}

.food-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.food-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.food-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.food-price {
  color: #C70209;
  font-weight: 600;
  font-size: 32rpx;
}

.food-quantity {
  color: #999;
  font-size: 28rpx;
}

.expand-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 0 0;
  margin-top: 16rpx;
  border-top: 1px solid #f0f0f0;
}

.expand-text {
  font-size: 28rpx;
  color: #666;
  margin-right: 8rpx;
}

.expand-icon {
  font-size: 28rpx;
  color: #999;
  transition: transform 0.3s ease;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.control-btn {
  width: 50rpx;
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  border: 1px solid #007aff; /* 蓝色边框 */
  color: #007aff; /* 蓝色文字 */
  border-radius: 50%; /* 圆形按钮 */
  margin: 0 10rpx;
}

.quantity {
  font-size: 28rpx;
  margin: 0 10rpx;
}

.sold-out {
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  color: #999;
}

.footer-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-top: 1px solid #eee; /* 顶部边框 */
  background-color: #ffffff; /* 白色背景 */
  /* position: fixed; /* 底部固定 */
  /* bottom: 0;
  width: 100%; */
}

.total-info {
  display: flex;
  align-items: center;
}

.total-count {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.total-price {
  font-size: 36rpx;
  color: #C70209; /* 红色总价 */
  font-weight: bold;
}

.checkout-button {
  background-color: #C70209; /* 红色按钮 */
  color: #ffffff;
  font-size: 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  padding: 0 40rpx;
}

.button-disabled {
  background-color: #cccccc !important;
  opacity: 0.7;
}

/* 购物车模态框样式 */
.cart-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: flex-end; /* 模态框从底部弹出 */
  z-index: 1000; /* 确保在其他内容之上 */
}

.cart-modal-content {
  width: 100%;
  height: 70%; /* 模态框高度 */
  background-color: #ffffff; /* 白色背景 */
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 隐藏溢出内容 */
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
}

.close-button {
  font-size: 40rpx;
  color: #999;
}

.selected-products-list {
  flex: 1; /* 填充剩余空间并允许滚动 */
  padding: 0 30rpx;
}

.selected-product-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee; /* 分隔线 */
}

.selected-product-image {
   width: 100rpx;
  height: 100rpx;
  background-color: #f5f5f5; /* 占位背景色 */
  margin-right: 20rpx;
  border-radius: 8rpx;
  object-fit: cover;
}

.selected-product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.selected-product-name {
  font-size: 28rpx;
  font-weight: bold;
}

.selected-product-price {
  font-size: 28rpx;
  color: #C70209; /* 红色价格 */
  font-weight: bold;
}

.selected-quantity-controls {
   display: flex;
   align-items: center;
}

.selected-quantity {
   font-size: 28rpx;
   margin: 0 10rpx;
}

.modal-footer-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-top: 1px solid #eee;
  background-color: #ffffff;
}

.modal-total-info {
  display: flex;
  align-items: center;
}

.modal-total-label {
    font-size: 28rpx;
    color: #333;
    margin-right: 10rpx;
}

.modal-total-count {
  font-size: 28rpx;
  color: #C70209; /* 红色件数 */
  margin-right: 20rpx;
}

.modal-total-price {
  font-size: 36rpx;
  color: #C70209; /* 红色总价 */
  font-weight: bold;
}

.pay-button {
  background-color: #C70209; /* 红色按钮 */
  color: #ffffff;
  font-size: 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  padding: 0 40rpx;
}

.empty-list {
  text-align: center;
  padding: 40rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300rpx;
}

.empty-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 20rpx;
}
</style> 